<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2020/5/8
 * Time: 11:45
 */
namespace app\api\controller;

use app\common\controller\Api;

/**
 * 留言api
 * Class Message
 * @package app\api\controller
 */
class Message extends Api{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 提交留言内容
     * @throws \think\Exception
     */
    public function add(){
        $content=$this->request->request('content')?trim($this->request->request('content')):$this->error('请输入留言！');
        $mobile=$this->request->request('mobile')?trim($this->request->request('mobile')):$this->error('请输入手机号！');
        $nickname=$this->request->request('nickname')?trim($this->request->request('nickname')):$this->error('请输入昵称！');

        //获得用户ip
        $ip=$this->request->ip();

        //根据手机号是否存在用户信息
        $user=db('user')->where('mobile="'.$mobile.'"')->field('id,status')->find();
        //用户不存在添加用户
        if(empty($user)){
            $defaultGroup=model('user_group')->where('status="normal" and name="默认组"')->field('id')->find();
            $userData['group_id']=$defaultGroup['id'];
            $userData['joinip']=$ip;
            $userData['mobile']=$mobile;
            $userData['nickname']=$nickname;
            $userData['jointime']=time();
            $userData['status']='normal';
            model('user')->allowField(true)->save($userData)?$user=db('user')->where('joinip="'.$ip.'"')->field('id,status')->find():$this->error('系统异常！');
        }
        if($user['status']=='hidden') $this->error('用户状态异常！');

        //当前用户是否有提交过这个问题
        db('message')->where('user_id='.$user['id'].' and content="'.$content.'"')->count()?$this->error('请不要重复留言！'):'';

        //添加问题
        $messageData['user_id']=$user['id'];
        $messageData['content']=$content;
        model('message')->allowField(true)->save($messageData)?'':$this->error('系统异常！');

        $this->success('提交成功.');
    }
}